package ai.leinao.notify.core.configuration;

import ai.leinao.notify.core.Notifier;
import ai.leinao.notify.core.NotifierRegistry;
import ai.leinao.notify.core.NotifyProperties;
import ai.leinao.notify.core.enums.NotifyType;
import ai.leinao.notify.core.template.Template;
import lombok.AllArgsConstructor;
import lombok.NonNull;

import java.util.List;
import java.util.Objects;

/**
 * 组合通知管理器
 *
 * @author zhong.wang
 * @date 2025/7/9
 */
@AllArgsConstructor
public class CompositeNotifierRegistry implements NotifierRegistry {
    /**
     * 通知管理器列表
     */
    private final List<NotifierRegistry> notifierRegistries;


    /**
     * 获取通知器
     *
     * @param notifyType 通知器类型
     * @param notifyId         通知器id
     * @return 通知器
     */
    @Override
    public <T extends Template> Notifier<T> getNotifier(@NonNull NotifyType notifyType, @NonNull String notifyId) {
        Notifier<T> notifier = null;
        for (NotifierRegistry registry : notifierRegistries) {
            notifier = registry.getNotifier(notifyType, notifyId);
            if(Objects.nonNull(notifier)){
                break;
            }
        }
        if(Objects.isNull(notifier)){
            throw new UnsupportedOperationException("不支持该通知类型:"+ notifyType.getType());
        }
        return notifier;
    }

    /**
     * 创建通知器
     *
     * @param properties 通知器属性
     * @return 通知器
     */
    @Override
    public <T extends Template> Notifier<T> createNotifier(@NonNull NotifyProperties properties) {
        Notifier<T> notifier = null;
        for (NotifierRegistry registry : notifierRegistries) {
           try {
               notifier = registry.createNotifier(properties);
           } catch (Exception e) {
           }
        }
        if(Objects.isNull(notifier)){
            throw new UnsupportedOperationException("不支持该通知类型:"+ properties.getNotifyType().getType());
        }
        return notifier;
    }
}
